﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using RN.ERP.Web.ModelService;
using RN.ERP.Web.EnterpriseService;
using RN.ERP.Web.PersonService;
using RN.ERP.Web.BasicService;
using System.Web.Script.Serialization;
using System.Configuration;
using Newtonsoft.Json;


namespace RN.ERP.Web.Handlers
{

    /// <summary>
    /// RegistryHandler 的摘要说明
    /// </summary>
    public class RegistryHandler : IHttpHandler
    {
        #region 属性和常量
        private const string EXPERT_POST_FUNCCODE = "expertRegistry";
        /// <summary>
        /// 系统编号
        /// </summary>
        public string SysCode
        {
            get
            {
                return ConfigurationManager.AppSettings["AppId"];
            }
        }
        #endregion

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "json";
            context.Response.ContentEncoding = System.Text.Encoding.UTF8;
            string action = context.Request["action"];
            string result = string.Empty;
            switch (action)
            {
                case "Corp":
                    result = CorpReg(context);
                    break;
                case "Expert":
                    result = ExpertReg(context);
                    break;
                default: break;
            }
            ModelService.OperationResult resultModel = JsonConvert.DeserializeObject<ModelService.OperationResult>(result);
            var json = new { result = resultModel == null ? 0 : resultModel.ReturnValue, message = resultModel == null ? "注册失败" : resultModel.Message };
            //var json = new { result = 1, message = "测试测试" };
            JavaScriptSerializer seriailzer = new JavaScriptSerializer();
            context.Response.Write(seriailzer.Serialize(json));
            context.Response.End();
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        private string CorpReg(HttpContext context)
        {
            EnterpriseServiceClient enterpriseService = new EnterpriseServiceClient();
            ModelService.Tb_Corp_CompanyInfo corpModel = CreateCorpInfo(context);
            ModelService.T_Sys_Users userModel = CreateSysUser(context);
            string corp = JsonConvert.SerializeObject(corpModel);
            string user = JsonConvert.SerializeObject(userModel);
            string areaCode = ConfigurationManager.AppSettings["sysArea"] == null ? string.Empty : ConfigurationManager.AppSettings["sysArea"];
            string result = enterpriseService.CorpReg(corp, user, areaCode);
            return result;
        }

        private string ExpertReg(HttpContext context)
        {
            OperationResult ret = new OperationResult();
            ret.ReturnValue = 0;
            ret.Result = false;
            ret.Message = "注册失败";
            
            ////手机验证码验证
            bool mobileVal = MobileValidation(context);
            if (mobileVal == false)
            {
                ret.Message = "验证码验证不成功";
                return JsonConvert.SerializeObject(ret);
            }

            ////身份证号格式验证
            if (!ValidationHelper.CheckIDCard(context.Request["idCard"]))
            {
                ret.Message = "身份证格式不正确";
                return JsonConvert.SerializeObject(ret);  
            }

            PersonServiceClient personService=new PersonServiceClient();
            BasicServiceClient baseService=new BasicServiceClient();
            ModelService.T_Sys_Users userModel = CreateExpertUser(context);
            ModelService.Tb_Corp_CompanyInfo corpModel = CreateExpertCorpInfo(context);
            ModelService.tb_Emp_Manager expertModel = CreateExpert(context);
            try
            {
                expertModel.EmployeeType = baseService.GetExpertDBName(expertModel.DBType);
            }
            catch (Exception ex)
            {

            }
            string user = JsonConvert.SerializeObject(userModel);
            string corp = JsonConvert.SerializeObject(corpModel);
            string expert=JsonConvert.SerializeObject(expertModel);
            string result = personService.ExpertReg(user, corp, expert, string.Empty);
            return result;
        }

        private bool MobileValidation(HttpContext context)
        {
            bool ret = false;
            string mobile=context.Request["exMobile"];
            string vcode = context.Request["exCode"];
            if (!string.IsNullOrEmpty(mobile) && !string.IsNullOrEmpty(vcode))
            {
                try
                {
                    using (ZtbService.ZtbServiceClient zsc = new ZtbService.ZtbServiceClient())
                    {
                        bool rst = zsc.CheckPhoneCodeAppoint(mobile, vcode, SysCode, EXPERT_POST_FUNCCODE);
                        ret = rst;
                    }
                }
                catch (Exception ex)
                {
                }
            }
            return ret;
        }

        private ModelService.Tb_Corp_CompanyInfo CreateCorpInfo(HttpContext context)
        {
            ModelService.Tb_Corp_CompanyInfo rc = new ModelService.Tb_Corp_CompanyInfo();
            rc.AreaCode = context.Request["ucArea$hidCode"];
            rc.AreaCode2 = context.Request["ucArea$hidCityCode"];
            rc.tb_Corp_IsOuter = 0;//本省
            string citycode = context.Request["ucArea$hidCityCode"];
            //if (citycode != "02")
            //{
            //    rc.tb_Corp_IsOuter = 1;//外省
            //}
            rc.CorpName = context.Request["corpName"];
            rc.Email = context.Request["email"];
            rc.Tel = context.Request["linkTel"];
            rc.Type = context.Request["DDLCorpUserType"];
            rc.AddFlag = false;
            rc.IsDel = false;
            rc.IsInOrOut = 1;
            rc.flagForCheckValidCorp = 0;
            rc.CertificateType = 1;
            string userType = context.Request["DDLCorpUserType"];
            rc.classID = !string.IsNullOrEmpty(userType) ? int.Parse(userType) : -1;
            string corpType = context.Request["DDLCorpType"];
            rc.CorpType = userType != null && !string.IsNullOrEmpty(corpType) ? int.Parse(corpType) : -1;
            rc.OrginazationCode = context.Request["orgCode"];
            rc.BussinessNum = context.Request["bussinessNum"];
            rc.RegProv = "00";
            rc.RegCity = context.Request["ucArea$hidCityCode"]; ;
            rc.RegDistrict = context.Request["ucArea$hidCode"];
            rc.CertNumber = new byte();
            string dogid = context.Request["hdnDogid"];
            int dig = -1;
            if (!string.IsNullOrEmpty(dogid) && int.TryParse(dogid, out dig))
            {
                rc.dogid = dig;
            }
            return rc;
        }

        private ModelService.Tb_Corp_CompanyInfo CreateExpertCorpInfo(HttpContext context)
        {
            ModelService.Tb_Corp_CompanyInfo rc = new ModelService.Tb_Corp_CompanyInfo();
            rc.AreaCode = "00";
            rc.AreaCode2 = "00";
            rc.tb_Corp_IsOuter = 0;//本省
            string citycode = context.Request["ucAreaExp$hidCityCode"];
            rc.CorpName = context.Request["excorpName"];
            rc.Email = context.Request["exEmail"];
            rc.Tel = context.Request["exlinkTel"];

            string userType = context.Request["DDLCorpUserType_Expert"];
            rc.Type = userType;
            rc.AddFlag = false;
            rc.IsDel = false;
            rc.IsInOrOut = 1;
            rc.flagForCheckValidCorp = 0;
            rc.CertificateType = 1;
            rc.classID = !string.IsNullOrEmpty(userType) ? int.Parse(userType) : -1;
            rc.CorpType = -1;
            rc.OrginazationCode = context.Request["exorgCode"];
            rc.RegProv = "00";
            rc.RegCity = string.Empty; 
            rc.RegDistrict = string.Empty
;
            rc.CertNumber = new byte();
            string dogid = context.Request["hdnexDogid"];
            int dig = -1;
            if (!string.IsNullOrEmpty(dogid) && int.TryParse(dogid, out dig))
            {
                rc.dogid = dig;
            }
            return rc;
        }

        private ModelService.T_Sys_Users CreateSysUser(HttpContext context)
        {
            ModelService.T_Sys_Users u = new ModelService.T_Sys_Users();
            u.AreaName = "";
            u.AreaCode = context.Request["ucArea$hidCityCode"];
           // u.ScopeAreaCode = context.Request["ucArea$hidCityCode"];
            u.bDeleted = 0;
            u.CALaunched = false;
            u.bSuperAdmin = 0;
            string userType = context.Request["DDLCorpUserType"];
            u.bGrade = userType != null && !string.IsNullOrEmpty(userType) ? int.Parse(userType) : -1;
            u.Role = userType;
            u.RoleID = userType != null && !string.IsNullOrEmpty(userType) ? int.Parse(userType) : -1;
            u.bLocked = 0;
            u.bStatus = 0;
            u.bValue = 0;
            u.ClassID = 2000;//代表是用户，非角色??????????????   
            u.CurrentTemplateType = 0;
            u.DeptID = 0;
            u.DeptName = context.Request["corpName"];
            u.DogID = -1;
            u.bSuperAdmin = 0;
            u.LastActiveDate = DateTime.Now;
            u.RegisterDate = DateTime.Now;
            u.RoleName = "";//?                   
            u.TreeID = 3336;//?                
            u.UserName = context.Request["userName"];
            u.Name = context.Request["corpName"];
            u.Pwd = context.Request["passWord"];
            u.ZZJGDM = context.Request["orgCode"];
            string dogid = context.Request["hdnDogid"];
            //不绑定狗号
            //int dig = -1;
            //if (!string.IsNullOrEmpty(dogid) && int.TryParse(dogid, out dig))
            //{
            //    u.DogID = dig;
            //}
            return u;
        }

        private ModelService.T_Sys_Users CreateExpertUser(HttpContext context)
        {
            ModelService.T_Sys_Users u = new ModelService.T_Sys_Users();
            u.AreaName = "";
            u.AreaCode = "00";
            // u.ScopeAreaCode = context.Request["ucArea$hidCityCode"];
            u.bDeleted = 0;
            u.CALaunched = false;
            u.bSuperAdmin = 0;
            u.bGrade =56;
            u.Role = "56";
            u.RoleID = 56;
            u.bLocked = 0;
            u.bStatus = 0;
            u.bValue = 0;
            u.ClassID = 2000;//代表是用户，非角色??????????????   
            u.CurrentTemplateType = 0;
            u.DeptID = 0;
            u.DeptName = context.Request["excorpName"];
            u.DogID = -1;
            u.bSuperAdmin = 0;
            u.LastActiveDate = DateTime.Now;
            u.RegisterDate = DateTime.Now;
            u.RoleName = "";//?                   
            u.TreeID = 3336;//?                
            u.UserName = context.Request["Name"];
            u.Name = context.Request["Name"];
            u.Pwd = context.Request["passWord"];
            u.ZZJGDM = context.Request["exorgCode"];
            u.userTel = context.Request["exMobile"];
            string dogid = context.Request["hdnexDogid"];
            //不绑定狗号
            //int dig = -1;
            //if (!string.IsNullOrEmpty(dogid) && int.TryParse(dogid, out dig))
            //{
            //    u.DogID = dig;
            //}
            return u;
        }

        private ModelService.tb_Emp_Manager CreateExpert(HttpContext context)
        {
            ModelService.tb_Emp_Manager m = new ModelService.tb_Emp_Manager();
            m.AreaCode = "00";
            m.isZZEmp = 3;
            m.ClassId = 8065;
            m.TypeFlag = "-1";
            m.Name = context.Request["Name"];
            m.IDCard = context.Request["idCard"];
            m.Tel = context.Request["exlinkTel"];
            m.MobileTel = context.Request["exMobile"];
            m.EMail = context.Request["exEmail"];
            m.FlowCode = "0";
            m.DogID = -1;
            m.empdogid = -1;
            m.DBType = context.Request["ucDbExp$hidCode"];

            if (!String.IsNullOrEmpty(m.ExpertCardID = context.Request["expertCode"]))
            {
                m.isShenBao = 3;////以此来标识这是广联达导入的老专家
                DateTime date = DateTime.Now;
                if (m.ExpertCardID.StartsWith("AFS"))////普通专家
                {
                    if (DateTime.TryParse(context.Request["expertCodeBeginDate"], out date))
                    {
                        m.ExpertCardBeginDate = date;
                    }
                }
                else////资深专家
                {
                    m.IsSeniorExpert = true;
                    if (DateTime.TryParse(context.Request["expertCodeBeginDate"], out date))
                    {
                        m.SeniorExpertCardDate = date;
                    }
                }
                if (DateTime.TryParse(context.Request["expertCodeEndDate"], out date))
                {
                    m.ExpertCardEndDate = date;
                }
            }
            
            return m;
        }
    }
}
